<template>
  <div class="container">
      <div class="menu-nav">
        <div class="logo">
          <img src="@/assets/仓鼠.png" width="150" title="code by Mr.Hongtao"/>
          <h2 style="padding-left: 20px;user-select: none" title="code by Mr.Hongtao" >程序引用点位管理</h2>
          <small style="padding-left: 10px;margin-top: -20px;user-select: none"><el-tag type="danger" size="mini">bata版</el-tag></small>
        </div>
        <div class="menu">
          <el-input placeholder="在此检索功能" v-model="searchText">
            <template slot="append"><el-button @click="searchFunction"><i class="el-icon-search" /></el-button></template>
          </el-input>
          <el-button plain type="primary" style="margin-left: 10px" @click="addFunction">新增功能</el-button>
        </div>
      </div>
      <div class="content">
        <div class="left-content">
          <!--  列表  -->
          <div class="title">
            <el-badge :value="functionList.length" class="item" type="primary">
              功能列表
            </el-badge>
          </div>
          <div class="list">
            <el-table
                :show-header="false"
                @row-click="findModuleList"
                highlight-current-row
                :data="functionList"
                style="width: 100%">
              <el-table-column
                  prop="functionName"
              >
                <template slot-scope="scope">
                  {{ scope.row.functionName }}
                </template>
              </el-table-column>
              <el-table-column
                  width="80px">
                <template slot-scope="scope">
                  <el-tag :type="scope.row.functionType === '页面展示'? 'success' : 'primary'" v-show="scope.row.functionType">{{ scope.row.functionType }} </el-tag>
                </template>
              </el-table-column>
              <el-table-column
                width="50px">
                <template slot-scope="scope" >
                  <el-dropdown  @command="(cmd) => handleCommand(cmd, scope.row)" trigger="click">
                    <span class="el-dropdown-link">
                      <i class="el-icon-setting" style="padding-left: 5px;"/>
                    </span>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item command="addModule">添加模块</el-dropdown-item>
                      <el-dropdown-item command="edit">编辑</el-dropdown-item>
                      <el-dropdown-item command="delete">删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>

                </template>
              </el-table-column>

            </el-table>
            <!--<div class="pagination">-->
            <!--  <div v-if="functionPage.pageNum === functionPage.pages">没有更多了</div>-->
            <!--  <div v-else>下拉刷新</div>-->
            <!--</div>-->
          </div>

        </div>
        <div class="right-content">
          <el-empty :image-size="300" style="height: 80%;" v-if="childList.length === 0"></el-empty>
          <div class="child-list" v-else v-for="(item, index) in childList" :key="index">
            <div class="child-title">
              <div class="left">
                <div style="width: 8px;height:15px;background-color: #3b82f6;margin-right: 10px"></div>
                <span>{{item.moduleName}}</span>
              </div>
              <div class="right">
                <!--<el-button size="mini" style="">常量</el-button>-->
                <el-button size="mini" @click="generateEnum(item)" style="margin-right: 10px;">枚举</el-button>
                <el-dropdown  @command="(cmd) => handleCommandModule(cmd, item)" trigger="click">
                    <span class="el-dropdown-link">
                      <i class="el-icon-setting" style="padding-left: 5px;"/>
                    </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="edit">调整点位</el-dropdown-item>
                    <el-dropdown-item command="delete">删除模块</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>

            </div>
            <div class="child-table">
              <el-table
                  :data="item.pointList"
                  size="mini"
                  max-height="300"
                  style="width: 100%;">

                <el-table-column
                    type="index"
                    label="序号"
                    width="80"/>

                <el-table-column
                    prop="pointId"
                    label="点位ID"
                    width="100"/>

                <el-table-column
                    prop="pointName"
                    label="点位名称"
                    show-overflow-tooltip
                    width="260"/>

                <el-table-column
                    prop="pointEngName"
                    label="点位英文名称"
                    show-overflow-tooltip
                    width="180"/>

                <el-table-column
                    prop="customAlias"
                    show-overflow-tooltip
                    min-width="160"
                    label="自定义别名(全局唯一)"/>

                <el-table-column
                    prop="dataType"
                    show-overflow-tooltip
                    label="点位类型"/>

                <el-table-column
                    prop="instanceName"
                    show-overflow-tooltip
                    label="所属实例"/>

                <el-table-column
                    show-overflow-tooltip
                    prop="path"
                    label="所属实例"
                    width="160"/>
              </el-table>
            </div>
          </div>
        </div>
      </div>

    <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        fullscreen
        width="30%">
      <span>这是一段信息</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 枚举代码展示对话框 -->
    <el-dialog
        title="Java枚举代码"
        :visible.sync="enumDialogVisible"
        width="60%"
        :before-close="handleCloseEnum">
      <el-input
          type="textarea"
          :rows="20"
          placeholder="Java枚举代码将显示在这里"
          v-model="enumCode"
          readonly>
      </el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="enumDialogVisible = false">关 闭</el-button>
        <el-button type="primary" @click="copyEnumCode" v-if="enumCode">复 制</el-button>
      </span>
    </el-dialog>

    <!-- 弹框 - 功能新增修改 -->
    <el-dialog
        :title="functionTitle"
        :visible.sync="dialogFunctionVisible"
        width="30%"
        :before-close="handleClose2">
        <el-form label-width="80px" :model="functionForm">
          <el-form-item label="功能名称">
            <el-input v-model="functionForm.functionName"></el-input>
          </el-form-item>
          <el-form-item label="功能描述">
            <el-input v-model="functionForm.functionDesc"></el-input>
          </el-form-item>
          <el-form-item label="数据类型">
            <el-select v-model="functionForm.functionType" placeholder="请选择">
              <el-option
                  v-for="item in dataTypes"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-select>

          </el-form-item>
        </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogFunctionVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditFunction">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 弹框 - 添加模块 -->
    <el-dialog
        title="添加模块"
        :visible.sync="dialogModuleVisible"
        width="30%">
      <el-form :model="moduleForm" class="demo-form-inline" label-position="right" label-width="100px">
        <el-form-item label="模块名称">
          <el-input v-model="moduleForm.moduleName" placeholder="模块名称"></el-input>
        </el-form-item>
        <el-form-item label="模块英文名称">
          <el-input v-model="moduleForm.moduleEngName" placeholder="大写、下划线分隔"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogModuleVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAddModule">确 定</el-button>
      </span>
    </el-dialog>


  </div>
</template>

<script>
import {
  findFunctionListApi,
  findModuleListApi,
  editFunctionApi,
  createFunctionApi,
  deleteFunctionApi,
  findFunctionApi,
  createModuleApi,
  deleteModuleApi

} from '@/api/point'
export default {
  name: "",
  data() {
    return {
      searchText: null,
      functionTitle: null,
      functionList: [],
      childList: [

      ],
      dialogVisible: false,
      dialogFunctionVisible: false,
      dialogModuleVisible: false,
      enumDialogVisible: false,
      enumCode: '',
      functionPage: {data: [], pageNum: 1, pageSize: 20, pages: 2},
      functionForm: {
        id: null,
        functionName: '默认名称',
        functionDesc: '默认缓存',
        functionType: '默认类型'
      },
      dataTypes: [
        {
          value: '页面展示',
          label: '页面展示'
        },
        {
          value: '定时任务',
          label: '定时任务'
        },
      ],
      value: '',
      moduleForm: {
        functionId: null,
        moduleName: '',
        moduleEngName: ''
      }
    }
  },
  mounted() {
    this.getFunctionList();
  },
  methods: {
    searchFunction() {
      findFunctionApi(this.searchText).then(res=>{
        this.functionList = res.data;
      })
    },
    submitEditFunction(){
      if (this.functionForm.id !== null) {
        editFunctionApi(this.functionForm).then(()=>{
          this.$message({
            type: 'success',
            message: '编辑成功!'
          });
        }).finally(()=>{
          this.getFunctionList();
        });
      }else {
        createFunctionApi(this.functionForm).finally(()=>{
          this.getFunctionList();
        });
      }
      this.dialogFunctionVisible = false;
    },
    getFunctionList() {
      findFunctionListApi().then(res => {
        this.functionList = res.data;
      })
    },
    findModuleList(row) {
      findModuleListApi(row.id).then(res=>{
        this.childList = res.data;
      })
    },
    handleCommand(command, row) {
      switch (command) {
        case 'edit':
          this.editFunction(row);
          break;
        case 'delete':
          this.deleteFunction(row);
          break;
        case "addModule":
          this.addModule(row);
          break;
      }
    },
    handleCommandModule(command, item) {
      switch (command) {
        case 'edit':
          this.addChild(item);
          break;
        case 'delete':
          this.deleteModuleItem(item);
          break;
      }
    },
    addChild(item) {
      this.$router.push(
          {
            path: '/edit',
            query:  {item: JSON.stringify(item)}
          }
      )
    },
    deleteModuleItem(item) {
      this.$confirm('此操作将永久删除【' + item.moduleName + '】模块的缓存文件, 是否继续?', '删除提示🚨', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteModuleOperation(item);
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    deleteModuleOperation(item) {
      deleteModuleApi(item.id).finally(()=>{
        findModuleListApi(item.functionId).then(res=>{
          this.childList = res.data;
        });
        this.dialogModuleVisible = false;
      });
    },

    // 功能管理
    // 新增功能
    addFunction() {
      this.dialogFunctionVisible = true;
      this.functionTitle = "新增功能";
      this.functionForm = {
        id: null,
        functionName: '',
        functionDesc: '',
        functionType: ''
      }
    },

    // 编辑功能
    editFunction(row) {
      this.dialogFunctionVisible = true;
      this.functionTitle = "编辑功能信息";
      this.functionForm = {
        id: row.id,
        functionName: row.functionName,
        cacheName: row.cacheName || '',
        functionType: row.functionType
      }
    },

    // 删除功能
    deleteFunction(row) {
      this.$confirm('此操作将永久删除【' + row.functionName + '】功能的缓存文件, 是否继续?', '删除功能提示🚨', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteFunctionOperation(row);
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    deleteFunctionOperation(row) {
      // 删除操作
      deleteFunctionApi(row.id).finally(()=>{
        this.getFunctionList();
      })
    },
    addModule(row) {
      this.dialogModuleVisible = true;
      this.moduleForm = {
        functionId: row.id,
        moduleName: '',
        moduleEngName: ''
      }

    },
    submitAddModule() {
      createModuleApi(this.moduleForm).then(()=>{
        this.$message({
          type: 'success',
          message: '添加模块成功'
        })
      }).catch(()=>{
        this.$message({
          type: 'error',
          message: '添加模块失败'
        })
      }).finally(()=>{
        findModuleListApi(this.moduleForm.functionId).then(res=>{
          this.childList = res.data;
        });
        this.dialogModuleVisible = false;
      })
    },

    //
    generateEnum(item) {
      // 生成Java枚举类代码
      let enumCode = `public enum ${this.formatEnumName(item.moduleEngName)} {\n    //枚举值由系统自动生成\n`;
      
      // 添加枚举项
      item.pointList.forEach((row, index) => {
        // 处理点位名称作为枚举项（优先使用pointEngName，如果没有则使用pointName）
        const pointEnumName = this.formatEnumItemName(row.pointEngName || row.pointName);
        const pointId = row.pointId || '';
        const pointName = row.pointName || '';
        
        // 添加枚举项，最后一个不加逗号
        if (index === item.pointList.length - 1) {
          enumCode += `    ${pointEnumName}(${pointId}, "${pointName}");\n`;
        } else {
          enumCode += `    ${pointEnumName}(${pointId}, "${pointName}"),\n`;
        }
      });
      
      // 添加私有属性
      enumCode += `\n    private final Integer pointId;\n`;
      enumCode += `    private final String pointName;\n\n`;
      
      // 添加构造函数
      enumCode += `    ${this.formatEnumName(item.moduleEngName)}(Integer pointId, String pointName) {\n`;
      enumCode += `        this.pointId = pointId;\n`;
      enumCode += `        this.pointName = pointName;\n`;
      enumCode += `    }\n\n`;
      
      // 添加getter方法
      enumCode += `    public Integer getPointId() {\n`;
      enumCode += `        return pointId;\n`;
      enumCode += `    }\n\n`;
      
      enumCode += `    public String getPointName() {\n`;
      enumCode += `        return pointName;\n`;
      enumCode += `    }\n`;
      enumCode += `}\n`;
      
      // 显示弹窗
      this.enumCode = enumCode;
      this.enumDialogVisible = true;
    },
    
    // 格式化枚举类名
    formatEnumName(title) {
      // 移除空格和特殊字符，采用驼峰命名
      return title.replace(/[^a-zA-Z0-9\u4e00-\u9fa5]/g, '')
        .replace(/\s+/g, '')
        .replace(/^[0-9]/, '_$&')
        .replace(/[\u4e00-\u9fa5]/g, function(word) {
          return word;
        }) || 'UnnamedEnum';
    },
    
    // 格式化枚举项名称
    formatEnumItemName(pointName) {
      // 将点位名称转换为合法的枚举项名称
      let name = pointName.replace(/\s+/g, '_')           // 空格替换为下划线
        .replace(/[^a-zA-Z0-9_\u4e00-\u9fa5]/g, '')      // 移除非字母数字和中文字符
        .toUpperCase();                                   // 转为大写
      
      // 如果处理后为空或数字开头，则添加前缀
      if (!name || /^[0-9]/.test(name)) {
        name = 'ITEM_' + name;
      }
      
      // 如果全为数字，也添加前缀
      if (/^[0-9_]+$/.test(name)) {
        name = 'ITEM_' + name;
      }
      
      return name || 'UNKNOWN_ITEM';
    },
    
    // 复制枚举代码到剪贴板
    copyEnumCode() {
      const textarea = document.createElement('textarea');
      textarea.value = this.enumCode;
      document.body.appendChild(textarea);
      textarea.select();
      document.execCommand('copy');
      document.body.removeChild(textarea);
      this.$message({
        message: '代码已复制到剪贴板',
        type: 'success'
      });
    },
    
    // 关闭枚举对话框
    handleCloseEnum() {
      this.enumDialogVisible = false;
    },
    
    // 关闭功能对话框
    handleClose2() {
      this.dialogFunctionVisible = false;
    }
  }
}
</script>

<style scoped lang="scss">
.container {
  width: 100vw;
  height: 100vh;

  .menu-nav {
    height: 10%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #6c757d;
    color: #fff;
    .logo {
      display: flex;
      align-items: center;
    }
    .menu {
      display: flex;
      justify-content: right;
      align-items: center;
      margin-right: 20px;
    }
  }

  .content {
    height: calc(100vh - 10%);
    display: flex;

    .left-content {
      width: 20%;
      height: 100%;
      background-color: #e9ecef;
      .title {
        height: 10%;
        color: #6e7074;
        font-size: 18px;
        user-select: none;
        background-color: #ffffff;
        padding: 25px 8px 3px;
      }
      .list {
        height: 90%;
        overflow-y: auto;
        background-color: #ffffff;
        .pagination {
          height: 5%;
          display: flex;
          justify-content: center;
          align-items: center;
          font-size: 12px;
          color: #6c757d;
        }
      }

    }

    .right-content {
      flex: 1;
      background-color: #f8f9fa;
      overflow-y: auto;
      .child-list {
        transition: transform 0.3s, box-shadow 0.3s; /* 添加过渡效果 */
        border-top-left-radius: 10px;
        border-top-right-radius: 10px;
        margin: 20px;
        color: #6e7074;
        .child-title {
          padding: 8px;
          display: flex;
          justify-content:space-between;
          align-items: center;
          .left {
            display: flex;
            justify-content: left;
            align-items: center;
          }
          .right {
            margin-right: 0px;
          }
        }
        .child-table {

        }
      }
      .child-list:hover {
        //transform: scale(1.001); /* 放大效果 */
        box-shadow: 0 2px 22px 0 rgba(0, 0, 0, 0.1); /* 高亮阴影效果 */
        z-index: 1; /* 确保放大元素覆盖其他元素 */
        border-top-left-radius: 10px;
        border-top-right-radius: 10px;
      }
    }


  }
}

.custom-text-btn {
  color: #ff0000; /* 红色文字 */
}

//显示时按钮样式
.el-button--inblack{ //需要更改的按钮类型
  background: #060606 !important;
  border-color: #060606 !important;
  color: #fff !important;

  //移入时按钮样式
  &:hover {
    &:not(.is-disabled) {
      background: #706e6e !important;
      border-color: #706e6e !important;
      color: #FFF !important;
    }
  }
}
//禁用时按钮样式
.el-button--inblack.is-disabled {
  background: #706e6e !important;
  border-color: #706e6e !important;
  color: #FFF !important;
}

.el-dropdown-link {
  cursor: pointer;
  color: #409EFF;
}
.el-icon-arrow-down {
  font-size: 12px;
}

.el-dropdown {
  padding-right: 10px;
  // padding-bottom: 10px; //这样修改弹框上下位置不可以，
}


/* 全局样式或使用 /deep/、::v-deep 穿透 scoped */
::v-deep .el-table__body tr.current-row > td {
  background-color: #65789b !important; /* 你想要的颜色 */
  color: #fff !important; /* 选中行的文字颜色 */
}


</style>